-module(echo_server).
-compile(export_all).

start() ->
    start(12345).

start(Port) ->
    {ok, Listen} = gen_tcp:listen(Port, [binary, 
        {reuseaddr, true}, {packet,0}, {active, true}]),
    accept(Listen, 0).

accept(Listen, Count) ->
    case gen_tcp:accept(Listen) of
        {ok, Socket} ->
            spawn(fun() -> handle(Socket) end),
            io:format("connected:~p~n", [Count]),
            accept(Listen, Count+1);
        {error, Reason} ->
            {error, Reason}
    end.

handle(Socket) ->
    receive
        {tcp, Socket, Bin} ->
            gen_tcp:send(Socket, Bin),
            gen_tcp:close(Socket);
        {tcp_closed, Socket} ->
            close     
    end.
